package com.questionnaires.repository;

import com.questionnaires.model.Question;
import com.questionnaires.model.Questionnaire;
import com.questionnaires.model.Response;
import com.questionnaires.model.UserResponse;
import com.questionnaires.utils.ResponsePercentage;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author adriana.calina.oros@gmail.com
 */

@Repository(value="userResponseRepository")
public class UserResponseRepositoryImpl implements UserResponseRepository{

    @Autowired
    private SessionFactory sessionFactory;


    @Transactional
    public void insert(UserResponse userResponse){
        sessionFactory.getCurrentSession().save(userResponse);
    }

    @Transactional
    public void update(UserResponse userResponse){
        sessionFactory.getCurrentSession().update(userResponse);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public UserResponse findByResponse(Response response){
        Query query=sessionFactory.getCurrentSession().createQuery("from UserResponse userResponse " +
                "where userResponse.response.id=:responseId");
        query.setLong("responseId",response.getId());
        if (query.list().isEmpty()){
            return null;
        }
        return (UserResponse)query.list().get(0);
    }
    
    /*@Transactional
    public List<ResponsePercentage> getResponsePercentage(Question question){
        String sql="select ur.response_id,(ur.nr_rasp *100)/ " +
                "(SELECT sum(nr_rasp)" +
                "from users_responses u inner join responses r " +
                "on u.response_id=r.id" +
                "where r.question_id="+question.getId()+ ") as percent" +
                "from users_responses ur" +
                "inner join responses rr" +
                "on ur.response_id=rr.id" +
                "where rr.question_id="+question.getId();
        Query query=sessionFactory.getCurrentSession().createSQLQuery(sql);
        List responseList=query.list();
        if (responseList.isEmpty()){
            return null;
        }
        else {
            List<ResponsePercentage> responsePercentageList=new ArrayList<ResponsePercentage>();
            for (Object obj: responseList){
                int a=1;
            }

            return responsePercentageList;
        }

    }*/


}
